/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef SLE_SEEK_IMPL_H
#define SLE_SEEK_IMPL_H

#include <condition_variable>
#include <mutex>
#include <chrono>
#include "sle_utils_observer_list.h"
#include "i_sle_seek.h"
#include "sle_seek_interface.h"
#include "sle_seek_callback_stub.h"
#include "sle_discover_seek_parcel.h"
#include "sle_host_interface.h"

namespace OHOS {
namespace NearLink {
namespace SleStandard {
class SleSeek::SleSeekImpl {
public:
    SleSeekImpl();
    ~SleSeekImpl();
    SleErrorCode CheckOperation();

    class SleSeekCallbackStubImpl;
    sptr<SleSeekCallbackStubImpl> callbackImpl_ = nullptr;

    sptr<ISleSeek> proxy_ = nullptr;
    sptr<IRemoteObject::DeathRecipient> deathRecipient_ = nullptr;
    SleObserverList<SleSeekCallback> callbacks_;
    std::condition_variable conditionVariable_;
    bool ready_ = false;
    std::mutex mtx_;
    std::mutex mutexProxy_;
    SleSeekState state_ = SLE_SEEK_ERROR_STATE;

private:
    void GetProxy();
    void ResetService(const wptr<IRemoteObject> &remote);
};

class SleSeek::SleSeekImpl::SleSeekCallbackStubImpl : public SleSeekCallbackStub {
public:
    SleSeekCallbackStubImpl(SleSeek::SleSeekImpl &impl) : impl_(impl) {}
    ~SleSeekCallbackStubImpl() = default;

    void OnSeekStateChange(int32_t state) override
    {
        impl_.state_ = (SleSeekState)state;
        impl_.ready_ = true;
        impl_.conditionVariable_.notify_one();
        impl_.callbacks_.ForEach([state](std::shared_ptr<SleSeekCallback> callback) {
            callback->OnSeekStateChange((SleSeekState)state);
        });
    }

    void OnSeekResult(SeekResult &result) override
    {
        SleSeekResult ret;
        result.ConvertToSleSeekResult(ret);
        impl_.callbacks_.ForEach([&ret](std::shared_ptr<SleSeekCallback> callback) {
            callback->OnSeekResult(ret);
        });
    }

private:
    SleSeek::SleSeekImpl &impl_;
    SLE_DISALLOW_COPY_AND_ASSIGN(SleSeekCallbackStubImpl);
};
} // SleStandard
}   // OHOS
}   // NearLink

#endif //SLE_SEEK_IMPL_H